package org.surfnet.oaaas.selenium;

import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.surfnet.oaaas.model.AccessTokenResponse;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.matchers.JUnitMatchers.containsString;

public class AuthorizationCodeTestIT extends SeleniumSupport {
	private String clientId = "authorization-server-admin-js-client";
	private String secret = "somesecret";

	@Test
	public void authCode() throws Exception {
		String accessTokenRedirectUri = startAuthorizationCallbackServer(clientId, secret); 
		System.out.println(accessTokenRedirectUri);
		
		
		WebDriver webdriver = getWebDriver();
		String responseType = "code";
		String scopes = "read,write";
		String url = String.format("%s/oauth2/authorize?response_type=%s&scope=%s&client_id=%s&redirect_uri=%s",
						baseUrl(), responseType, scopes, clientId, accessTokenRedirectUri);
		System.out.println("url:"+url);
		webdriver.get(url);

		login(webdriver, true);

		
		//oauthserver get /catchcode fom testserver
		//testserver througt hander deal request, and send request access token from oauthserver and put it ...
		
		
		
		// get token response
		String tokenResponse = getAuthorizationCodeRequestHandler().getTokenResponseBlocking();//?????
		System.out.println("tokenResponse:" + tokenResponse);
		
		AccessTokenResponse accessTokenResponse = getMapper().readValue(tokenResponse, AccessTokenResponse.class);
        System.out.println(accessTokenResponse);
        
		assertTrue(StringUtils.isNotBlank(accessTokenResponse.getAccessToken()));
		assertTrue(StringUtils.isBlank(accessTokenResponse.getRefreshToken()));
		assertTrue(StringUtils.isNotBlank(accessTokenResponse.getScope()));
		assertTrue(StringUtils.isNotBlank(accessTokenResponse.getTokenType()));
		assertEquals(accessTokenResponse.getExpiresIn(), 0L);
	}
	
	@Test
	public void invalidParams() {
		final WebDriver webdriver = getWebDriver();
		webdriver.get(baseUrlWith("/oauth2/authorize"));

		String pageSource = webdriver.getPageSource();
		assertThat(pageSource, containsString("The supported response_type values are 'token' and 'code'"));
	}
}
